import React, { useState } from 'react';
import { Button, Form, Input, List, Modal, Select, App as AntApp, Card, Typography, Popconfirm } from 'antd';
import { PlusOutlined, EditOutlined, DeleteOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-components';
import { useAppStore, ProviderConfig, OpenAIProvider } from './store';

const { Title, Text } = Typography;
const { Option } = Select;

const SettingsPage: React.FC = () => {
  const { appConfig, addProvider, updateProvider, deleteProvider, setActiveProviderId } = useAppStore();
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [editingProvider, setEditingProvider] = useState<ProviderConfig | null>(null);
  const [form] = Form.useForm();
  const { message } = AntApp.useApp();

  const showModal = (provider?: ProviderConfig) => {
    setEditingProvider(provider || null);
    form.setFieldsValue(provider || { type: 'OpenAI', model: 'gpt-3.5-turbo' });
    setIsModalVisible(true);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
    form.resetFields();
  };

  const onFinish = async (values: any) => {
    try {
      if (editingProvider) {
        await updateProvider({ ...editingProvider, ...values });
        message.success('Provider updated successfully!');
      } else {
        const newProvider: OpenAIProvider = {
          id: `provider_${Date.now()}`,
          type: 'OpenAI',
          ...values,
        };
        await addProvider(newProvider);
        message.success('Provider added successfully!');
      }
      setIsModalVisible(false);
      form.resetFields();
    } catch (error) {
      message.error(`Failed to save provider: ${error}`);
    }
  };

  return (
    <PageContainer title="Settings">
      <Card title="Active Provider">
        <Select
          style={{ width: 300 }}
          placeholder="Select an active provider"
          value={appConfig?.active_provider_id}
          onChange={(value) => setActiveProviderId(value)}
          allowClear
        >
          {appConfig?.providers.map(p => (
            <Option key={p.id} value={p.id}>{p.name}</Option>
          ))}
        </Select>
      </Card>

      <Card title="Provider Management" extra={<Button icon={<PlusOutlined />} onClick={() => showModal()}>Add Provider</Button>} style={{ marginTop: 16 }}>
        <List
          itemLayout="horizontal"
          dataSource={appConfig?.providers || []}
          renderItem={item => (
            <List.Item
              actions={[
                <Button icon={<EditOutlined />} onClick={() => showModal(item)}>Edit</Button>,
                <Popconfirm
                  title={`Delete ${item.name}?`}
                  onConfirm={() => deleteProvider(item.id)}
                  okText="Yes"
                  cancelText="No"
                >
                  <Button icon={<DeleteOutlined />} danger>Delete</Button>
                </Popconfirm>
              ]}
            >
              <List.Item.Meta
                title={item.name}
                description={`Type: ${item.type} | Model: ${item.type === 'OpenAI' ? item.model : 'N/A'}`}
              />
            </List.Item>
          )}
        />
      </Card>

      <Modal
        title={editingProvider ? 'Edit Provider' : 'Add Provider'}
        open={isModalVisible}
        onCancel={handleCancel}
        onOk={() => form.submit()}
        destroyOnClose
      >
        <Form form={form} layout="vertical" name="provider_form" onFinish={onFinish} initialValues={{ type: 'OpenAI', model: 'gpt-3.5-turbo' }}>
          <Form.Item name="type" label="Provider Type" rules={[{ required: true }]}>
            <Select disabled={!!editingProvider}>
              <Option value="OpenAI">OpenAI</Option>
              {/* Add other provider types here in the future */}
            </Select>
          </Form.Item>
          <Form.Item name="name" label="Name" rules={[{ required: true, message: 'Please input a name!' }]}>
            <Input />
          </Form.Item>
          <Form.Item name="api_key" label="API Key" rules={[{ required: true, message: 'Please input your API Key!' }]}>
            <Input.Password />
          </Form.Item>
          <Form.Item name="model" label="Model" rules={[{ required: true, message: 'Please input the model name!' }]}>
            <Input />
          </Form.Item>
        </Form>
      </Modal>
    </PageContainer>
  );
};

export default SettingsPage;